﻿using ContactSMS.Commons.QueryParameters;
using ContactSMS.Commons.Responses;
using ContactSMS.Domain;
using ContactSMS.Domain.Entity;
using ContactSMS.WebAPI.Common;
using ContactSMS.WebAPI.Controllers.Request;
using ContactSMS.WebAPI.Controllers.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ContactSMS.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class ContactsController : ControllerBase
    {
        private readonly IContactRepository _contactRepository;
        private readonly IPhoneRepository _phoneRepository;
        private readonly TokenService _tokenService;

        public ContactsController(IContactRepository contactRepository, IPhoneRepository phoneRepository, TokenService tokenService)
        {
            _contactRepository = contactRepository;
            _phoneRepository = phoneRepository;
            _tokenService = tokenService;
        }

        [HttpGet]
        public async Task<IActionResult> GetContacts([FromQuery] ContactQueryParameters parameters, int page = 1, int pageSize = 10)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            try
            {
                var contacts = await _contactRepository.GetContactsAsync(parameters, page, pageSize, userId);
                var resp = new ServiceResponse<ContactsSearchResponse>()
                {
                    Data = new ContactsSearchResponse
                    {
                        list = contacts.Contacts,
                        CurrentPage = page,
                        Pages = (int)contacts.TotalPages
                    }
                };
                return Ok(resp);
            }
            catch (Exception ex)
            {
                ServiceResponse<List<Contact>> resp = new ServiceResponse<List<Contact>>();
                resp.Success = false;
                resp.Message = "暂无数据";
                return StatusCode(500, resp);
            }
        }

        [HttpGet]
        [Route("{id:long}")]
        public async Task<IActionResult> GetById([FromRoute] long id)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            var result = await _contactRepository.GetContactByIdAsync(id, userId);
            //result.Phones = await _phoneRepository.GetPhoneByContactIdAsync(id);
            ServiceResponse<Contact> resp = new ServiceResponse<Contact> { Data = result };
            return Ok(resp);
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] AddContactRequest addContactRequest)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }

            var contactDomainModel = new Contact(addContactRequest.Name, addContactRequest.Company, addContactRequest.Position, addContactRequest.Note, userId);

            await _contactRepository.AddContactAsync(contactDomainModel);
            List<Phone> phonesDomainModel = new List<Phone>();
            if (addContactRequest.Phones != null)
            {
                foreach (var item in addContactRequest.Phones)
                {
                    var phoneDomainModel = new Phone(contactDomainModel.Id, item.Mobile, "test", userId);
                    await _phoneRepository.AddPhoneAsync(phoneDomainModel);
                    phonesDomainModel.Add(phoneDomainModel);
                    contactDomainModel.Phones = phonesDomainModel;
                }
            }
            ServiceResponse<Contact> resp = new ServiceResponse<Contact> { Data = contactDomainModel };
            return Ok(resp);
        }

        [HttpPut]
        [Route("{id:long}")]
        public async Task<IActionResult> Update([FromRoute] long id, [FromBody] AddContactRequest addContactRequest)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            ServiceResponse<Contact> resp = new ServiceResponse<Contact>();
            var result = await _contactRepository.GetContactByIdAsync(id);
            if (result == null)
            {
                resp.Success = false;
                resp.Message = "信息不存在";
                return BadRequest(resp);
            }
            var contactDomainModel = new Contact(addContactRequest.Name, addContactRequest.Company, addContactRequest.Position, addContactRequest.Note, userId);
            ;
            await _contactRepository.UpdateContactAsync(id, contactDomainModel);
            contactDomainModel = new Contact()
            {
                Id = id,
                UserId = userId,
                Name = contactDomainModel.Name,
                Company = contactDomainModel.Company,
                Note = contactDomainModel.Note,
                Position = contactDomainModel.Position,
                CreatTime = contactDomainModel.CreatTime,
                UpdateTime = contactDomainModel.UpdateTime,
            };
            List<Phone> phonesDomainModel = new List<Phone>();
            if (addContactRequest.Phones != null)
            {
                await _phoneRepository.DeletePhoneByContactIdAsync(contactDomainModel.Id);
                foreach (var item in addContactRequest.Phones)
                {
                    var phoneDomainModel = new Phone(contactDomainModel.Id, item.Mobile, item.Tag, userId);
                    ;
                    await _phoneRepository.AddPhoneAsync(phoneDomainModel);
                    phonesDomainModel.Add(phoneDomainModel);
                    contactDomainModel.Phones = phonesDomainModel;
                }
            }
            resp.Success = true;
            resp.Message = "获取成功";
            resp.Data = contactDomainModel;
            return Ok(resp);
        }

        [HttpDelete]
        [Route("{id:long}")]
        public async Task<IActionResult> DeleteById([FromRoute] long id)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            ServiceResponse<Contact> resp = new ServiceResponse<Contact>();
            var result = await _contactRepository.DeleteContactByIdAsync(id, userId);
            if (result == null)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return NotFound(resp);
            }
            await _phoneRepository.DeletePhoneByContactIdAsync(id);
            resp.Success = true;
            resp.Message = "删除成功";
            return Ok(resp);
        }

        [HttpPost]
        public async Task<IActionResult> DeleteContacts([FromBody] List<long> ids)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            ServiceResponse<List<Contact>> resp = new ServiceResponse<List<Contact>>();
            if (ids == null || ids.Count == 0)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return BadRequest(resp);
            }
            var deletedContacts = await _contactRepository.DeleteContactByIdsAsync(ids.ToArray(), userId);
            if (deletedContacts == null || deletedContacts.Count == 0)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return NotFound(resp);
            }
            await _phoneRepository.DeletePhoneByContactIdsAsync(ids.ToArray());
            resp.Success = true;
            resp.Message = "删除成功";
            resp.Data = deletedContacts;
            return Ok(resp);
        }
    }
}
